//
//  ReportViewController.swift
//  ANOA
//
//  Created by 王万里 on 16/10/9.
//  Copyright © 2025 aowang. All rights reserved.
//

import UIKit

enum ReportParameterType: String {
    case radio = "1"       // 单选
    case multiple = "2"  // 多选
    case text = "3"    // 文本
    case month = "4"   // 月份
    case date = "5"   // 日期
    case lov = "6"  // lov
    case year = "7" // 年份
}

class ReportViewController: UITableViewController {
    
    var reportParameters = [Report]()
    
    fileprivate var allParameter = [[ReportDetail]]()
    
    // 有左右不同项的时候，这个参数用来持有 当前选中的项的参数数组   持有所有的 包括显示和不显示
      var allParamItems = [ReportDetail]()
      var showParamItems = [ReportDetail]() // 只展示显示的
     var parameterDic = [String: String]()
    
    var zoneSegV:ZoneSegView = {
       let v = ZoneSegView()
//        v.backgroundColor = .clear
        v.zShowType = .all
        v.blockWidthMultipliedBy = 0.43

        v.isUserInteractionEnabled = true
        return v
    }()
    
//    fileprivate lazy var segment: UISegmentedControl = {
//        let segment = UISegmentedControl()
//        segment.frame = CGRect(x: 8, y: 15, width: KSGlobal.screenW - 16, height: 30)
//        segment.backgroundColor = UIColor.white
//        segment.tintColor = UIColor.gray
//        segment.addTarget(self, action: #selector(segmentAction(_:)), for: .valueChanged)
//        return segment
//    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        
        title = reportParameters.first?.reportName
        view.backgroundColor = UIColor.white
 
        tableView.rowHeight = 60
        tableView.tableFooterView = UIView()
        tableView.register(ReportFooter.self, forHeaderFooterViewReuseIdentifier: "ReportFooter")
        
        parameterDic = ReportConfig.sharedInstance.assemblyParameters(reportParameters.first!)
        // 过滤出 if_show 等于1 的细表项目
        allParameter = reportParameters.map({ para -> [ReportDetail] in
            
            var parameter = [ReportDetail]()
            if let det = para.details {
                for item in det {
                         parameter.append(item)
                 }
            }
       
            return parameter
        })
        
        if let para = allParameter.first {
            allParamItems = para
            showParamItems = allParamItems.filter { $0.ifShow == "1" }
        }
        // 头部 分区 过滤
        if reportParameters.count > 1 {
            let header = UIView(frame: CGRect(x: 0, y: 0, width: KSGlobal.screenW, height: 60))
            zoneSegV.frame = CGRect(x: 0, y: 0, width: KSGlobal.screenW, height: 44)
            var seArr = [SegmenttData]()
            let btns = reportParameters.map { $0.buttonNm }
            for i in 0..<btns.count {
//                segment.insertSegment(withTitle: btns[i], at: i, animated: true)
                seArr.append(SegmenttData(id: "", nm: btns[i]))
            }
//            segment.selectedSegmentIndex = 0
            zoneSegV.setCollecDataSource(arr: seArr)
            header.addSubview(zoneSegV)
            zoneSegV.collecSelected = { indx ,data  in
           
                self.allParamItems = self.allParameter[indx]
                self.showParamItems = self.allParamItems.filter { $0.ifShow == "1" }

                self.parameterDic = ReportConfig.sharedInstance.assemblyParameters(self.reportParameters[indx])
                self.tableView.reloadData()
            }
           

            
            tableView.tableHeaderView = header
        }
    }
    
//    @objc func segmentAction(_ sender: UISegmentedControl) {
//        let index = sender.selectedSegmentIndex
//        allParamItems = allParameter[index]
//        showParamItems = allParamItems.filter { $0.ifShow == "1" }
//
//        parameterDic = ReportConfig.sharedInstance.assemblyParameters(reportParameters[index])
//        tableView.reloadData()
//    }
    
    override func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        view.endEditing(true)
    }
    
    override var shouldAutorotate: Bool {
        return true
    }
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return UIInterfaceOrientationMask.portrait
    }
    
    override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
        return UIInterfaceOrientation.portrait
    }
    
}

extension ReportViewController {
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        let remark = reportParameters.first?.sOptRemark.unwrap
        if remark != "" {
            return showParamItems.count + 1
        } else {
            return showParamItems.count
        }
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.row == showParamItems.count {
            // 提示，tip, 文本展示，无操作
            let cell = tableView.dequeueReusableCell(withIdentifier: "ReportMarkCell") as! ReportMarkCell
            let remark = reportParameters.first?.sOptRemark
            cell.label.text = "\(remark.unwrap)"
            return cell
            
        } else {
            guard let type = showParamItems[indexPath.row].typeCs else {
                return UITableViewCell()
            }
          
            switch type {
                
            case ReportParameterType.multiple.rawValue: // 多选
                let cell = tableView.dequeueReusableCell(withIdentifier: "ReportCell") as! ReportCell
                
                cell.selectAction = { [unowned self] select in
                    self.parameterDic.updateValue(select, forKey: self.showParamItems[indexPath.row].titleNm!)
                }
                
                cell.reportParameter = showParamItems[indexPath.row]
                
                return cell
                
            case ReportParameterType.text.rawValue: // 文本
                let cell = tableView.dequeueReusableCell(withIdentifier: "ReportInputCell") as! ReportInputCell
                
                cell.selectAction = { [unowned self] select in
                    self.parameterDic.updateValue(select, forKey: self.showParamItems[indexPath.row].titleNm!)
                }
                 cell.reportParameter = showParamItems[indexPath.row]
                 return cell
     
            default: // 单选（时间 月份  公司）  lov
                let cell = tableView.dequeueReusableCell(withIdentifier: "ReportSelectCell") as! ReportSelectCell
                cell.delegate = self
                cell.controller = self
 
                cell.reportCellItemSelAct = { [unowned self] select in
                  
                    self.parameterDic.updateValue(select, forKey: self.showParamItems[indexPath.row].titleNm!)
                     
                }
                
                cell.reportParameter = showParamItems[indexPath.row]
                
                return cell
            }
        }
    }
    
    override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let footer = tableView.dequeueReusableHeaderFooterView(withIdentifier: "ReportFooter") as! ReportFooter
        
        footer.footerAction = { [unowned self] in
            self.view.endEditing(true)
            
            // 校验必填数据是否有填
              let vali = Validation()
              for item in self.showParamItems {
                if item.sBt == "1" {
                    let val = parameterDic[item.titleNm.unwrap]
                    vali.expression(!val.unwrap.isEmpty, msg: "\(item.titleCs.unwrap)必填")
                 }
            }
            guard vali.validate() else {
                return
            }
            
            self.pushReportViewController()
        }
        
        return footer
    }
    
    override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 60
    }
    
    fileprivate func pushReportViewController() {
        
        
        var index = zoneSegV.selectIndx
        
        if index < 0 {
            index = 0
        }
        KSLog(parameterDic)
        go2ChartForWeb_OA(url: BaseReportUrl, path: reportParameters[index].reportUrl.unwrap, title: reportParameters[index].reportName ?? "标题", parameters: parameterDic, currentVC: self)
    }
}

class ReportHelper: NSObject {
 
    private let ReportVersion = "ReportVersion"
    

    static let shared = ReportHelper()

    fileprivate override init() {} // 防止初始化

 
  

    // 报表的版本号
    func reportVersion() -> String? {
        return UserDefaults.standard.object(forKey: ReportVersion) as? String
    }

    func setReportVersion(_ version: String) {
        UserDefaults.standard.set(version, forKey: ReportVersion)
    }
 
}
